import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import { addState } from '@/store/user/user.slice'
import Card from '@/component/card/Card'
import md5 from 'js-md5'
import './login.less'
import { useState } from 'react'
import Input from '@/component/input/Input'
import Button from '@/component/button/Button'
import axios from '@/http'
import jwt from 'jwt-decode'
import { useNavigate } from 'react-router-dom'
const Login = () => {
  useSelector((store: any) => {
    return store.user
  }, shallowEqual)
  const nav = useNavigate()
  const dispatch = useDispatch()
  const [username, setUserName] = useState<string>('')
  const [password, setPassword] = useState<string>('')
  const changeUserName = (value: string) => {
    console.log(value)
    setUserName(value)
  }
  const changePassword = (value: string) => {
    setPassword(md5(value + 'ttzxhEncryption'))
  }
  console.log('render')
  const login = () => {
    axios
      .post('/user/login', {
        username,
        password
      })
      .then(res => {
        const userInfo = jwt(res.data)
        dispatch(addState(userInfo))
        nav('/blog')
      })
  }
  return (
    <div className="login">
      <div className="login-pane">
        <Card height="300px">
          <div className="login-pane-margin">
            <Input prop="username" label="用户名" change={changeUserName}></Input>
          </div>
          <div className="login-pane-margin">
            <Input prop="password" label="密码" type={'password'} change={changePassword}></Input>
          </div>
          <div className="login-pane-margin">
            <Button size="large" onClick={login}>
              登陆
            </Button>
          </div>
          <div className="login-pane-margin">
            <Button size="large" onClick={login}>
              注册
            </Button>
          </div>
          <div className="login-pane-margin">
            <Button size="small" text type="error">
              忘记密码
            </Button>
          </div>
        </Card>
      </div>
    </div>
  )
}
export default Login
